// 当用户按下tab chrome将输入交给插件，然后输入第一个字符之后触发此事件
(function () {

    window.queryBmList = queryBmList;
    window.loadBm = loadBm;
    window.tagsAll = [];

    let cacheBmList = [];

    loadBm();

    // 当用户的输入改变之后
    // text 用户的当前输入
    // suggest 调用suggest为用户提供搜索建议
    let lastQueryText;
    chrome.omnibox.onInputChanged.addListener((text, suggest) => {
        lastQueryText = text;
        setTimeout(function () {
            if (lastQueryText == text) {
                let result = queryBmList(text);
                result && result.length > 0 && suggest(result);
            }
        }, 300);

    });

    // 按下回车时事件，表示向插件提交了一个搜索
    chrome.omnibox.onInputEntered.addListener((text, disposition) => {
        if (lastQueryText == text) {
            chrome.tabs.create({ url: `preview.html?key=${text}` });
            return;
        }
        let queryOptions = { active: true };
        chrome.tabs.query(queryOptions, function (result) {
            chrome.tabs.update(result[0].id, { url: text });
        });

    });

    // 取消输入时触发的事件，注意使用上下方向键在搜索建议列表中搜搜也会触发此事件
    // chrome.omnibox.onInputCancelled.addListener(() => {
    //     console.log("[" + new Date() + "] omnibox event: onInputCancelled");
    // });

    // 设置默认的搜索建议，会显示在搜索建议列表的第一行位置，content省略使用用户当前输入的text作为content
    chrome.omnibox.setDefaultSuggestion({
        "description": "跳转后台页面检索"
    })

    // 加载chrome书签到缓存
    function loadBm(call) {
        chrome.bookmarks.getTree((bRoot) => {
            cacheBmList = [];
            // 书签栏书签
            // let chromeBmList = bRoot[0].children[0];
            let findBm = (object, prefix) => {

                let { id, title, url, children } = object;

                if (children) {
                    // 目录
                    children.forEach((item) => {
                        findBm(item, prefix + title + "/");
                    });
                } else {
                    // 书签
                    let titleArray = title.split("||");
                    let tags = [];
                    if (titleArray.length == 2) {
                        tags = titleArray[1].split(",");
                        title = titleArray[0];
                        tags.forEach(tag => {
                            if (window.tagsAll.indexOf(tag) == -1) {
                                window.tagsAll.push(tag);
                            }
                        })
                    }
                    cacheBmList.push({
                        id,
                        title: html2Escape(prefix + title),
                        url,
                        tags
                    });
                }
            }

            // chromeBmList.children.forEach(item => findBm(item, ""));
            findBm(bRoot[0], "");

            console.log("缓存书签完成", cacheBmList);
            call && call(cacheBmList);
        });
    }

    // 筛选书签
    function queryBmList(keyWords, fromPage = false) {
        if (!keyWords) return [];
        if (keyWords.trim() == '') return [];
        if (cacheBmList.length == 0) return [];

        let keywordList = keyWords.split(" ");

        return cacheBmList.filter(bm => {

            let { title, url, tags } = bm;

            let matchCount = 0;
            for (let idx = 0; idx < keywordList.length; idx++) {

                let oneKeyWords = keywordList[idx];

                if (PinyinMatch.match(title + tags.join(""), oneKeyWords)) {
                    matchCount++;
                } else if (url && url.indexOf(oneKeyWords) !== -1) {
                    matchCount++;
                }

            }

            return matchCount == keywordList.length;
            
        }).map(bm => {
            let result = {
                content: bm.url,
                description: bm.title,
            }
            if (fromPage) {
                result.id = bm.id;
                result.tags = bm.tags;
            }
            return result;
        });
    }

    function html2Escape(sHtml) {

        return sHtml.replace(/[<>&"]/g, function (c) {

            return { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c];

        });

    }


})();
